#include <iostream>
#include <string>

#include "../add_contact.pb.h"
#include "../contactException.h"
#include "../httplib.h"

void printInfo(const add_contact::AddContactRequest& add_req) {
    printf("name: %s\n", add_req.name().c_str());
    printf("age: %d\n", add_req.age());
    for (int j = 0; j < add_req.phones_size(); ++j) {
        add_contact::Phone phone = add_req.phones(j);
        printf("the %dst phone number: %s   %s\n", j + 1,
               phone.number().c_str(),
               phone.PhoneType_Name(phone.phone_type()).c_str());
    }
}

int main() {
    httplib::Server server;

    server.Post("/contacts/add", [](const httplib::Request& req,
                                    httplib::Response& resp) {
        std::cout << "收到 post 请求" << std::endl;

        add_contact::AddContactRequest req_add;
        add_contact::Response resp_add;

        try {
            // 1. 反序列化请求
            if (!req_add.ParseFromString(req.body)) {
                throw(ContactException("请求反序列化失败"));
            }

            // 2. 处理请求 (添加联系人 - 打印联系人信息)
            printInfo(req_add);

            // 3. 构造响应
            resp_add.set_is_success(true);
            resp_add.set_err_desc("OK");
            resp_add.set_uid("123132");

            // 4. 序列化响应
            std::string resp_str;
            if (!resp_add.SerializeToString(&resp_str)) {
                throw(ContactException("响应序列化失败"));
            }

            // 5. 发送响应
            resp.status = 200;
            resp.body = resp_str;
            resp.set_header("Content-Type", "application/protobuf");

        } catch (const ContactException& e) {
            resp.status = 500;
            resp_add.set_is_success(false);
            resp_add.set_err_desc(e.what());

            std::string resp_str;
            if (resp_add.SerializeToString(&resp_str)) {
                resp.body = resp_str;
                resp.set_header("Content-Type", "application/protobuf");
            }

            std::cout << "发生异常: " << e.what() << std::endl;
        }
    });

    server.listen("127.0.0.1", 8080);

    return 0;
}